import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN,INDEX_MAIN_PAGE_PATH, OAUTH2_LOGIN_PAGE_PATH } from '@/store/mutation-types'
import { generateIndexRouter, isOAuth2AppEnv } from '@/utils/util'
import { addMaterialRoutes } from './router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/user/login', '/user/register', '/user/register-result','/user/alteration'] // no redirect whitelist
whiteList.push(OAUTH2_LOGIN_PAGE_PATH)

router.beforeEach((to, from, next) => {
  //update-begin---author:scott ---date:2022-10-13  for：[jeecg-boot/issues/4091]多级路由缓存问题 #4091-----------
  //解决三级菜单无法缓存问题
  //参考： https://blog.csdn.net/qq_37322135/article/details/126013301
  //参考： https://blog.csdn.net/cwin8951/article/details/106644118
  if (to.matched && to.matched.length>3) {
    to.matched.splice(2, to.matched.length - 3)
  }
  //update-end---author:scott ---date::2022-10-13  for：[jeecg-boot/issues/4091]多级路由缓存问题 #4091--------------
  
  console.log('路由跳转:', to.path, '从:', from.path);
  NProgress.start() // start progress bar

  if (Vue.ls.get(ACCESS_TOKEN)) {
    console.log('检测到ACCESS_TOKEN存在');
    /* has token */
    if (to.path === '/user/login' || to.path === OAUTH2_LOGIN_PAGE_PATH) {
      console.log('已登录状态访问登录页，重定向到首页');
      next({ path: INDEX_MAIN_PAGE_PATH })
      NProgress.done()
    } else {
      if (store.getters.permissionList.length === 0) {
        console.log('权限列表为空，开始获取权限菜单');
        store.dispatch('GetPermissionList').then(res => {
              console.log('获取权限菜单成功:', res);
              let menuData = res.result.menu;
              
              // 确保菜单数据存在且为数组
              if (!menuData) {
                console.error('菜单数据为空!');
                notification.error({
                  message: '系统提示',
                  description: '菜单加载失败，请重新登录！'
                });
                store.dispatch('Logout').then(() => {
                  next({ path: '/user/login', query: { redirect: to.fullPath } });
                });
                return;
              }
              
              // 如果菜单数据是字符串，尝试解析为JSON
              if (typeof menuData === 'string') {
                try {
                  console.log('菜单数据是字符串，尝试解析为JSON');
                  menuData = JSON.parse(menuData);
                } catch (e) {
                  console.error('菜单数据解析失败:', e);
                  notification.error({
                    message: '系统提示',
                    description: '菜单数据格式错误，请重新登录！'
                  });
                  store.dispatch('Logout').then(() => {
                    next({ path: '/user/login', query: { redirect: to.fullPath } });
                  });
                  return;
                }
              }
              
              // 确保解析后的数据是数组
              if (!Array.isArray(menuData)) {
                console.error('菜单数据不是数组格式:', menuData);
                notification.error({
                  message: '系统提示',
                  description: '菜单数据格式不正确，请重新登录！'
                });
                store.dispatch('Logout').then(() => {
                  next({ path: '/user/login', query: { redirect: to.fullPath } });
                });
                return;
              }
              
              console.log('生成路由的菜单数据:', menuData);
              let constRoutes = [];
              try {
                constRoutes = generateIndexRouter(menuData);
                console.log('生成的路由配置:', constRoutes);
              } catch (e) {
                console.error('路由生成失败:', e);
                notification.error({
                  message: '系统提示',
                  description: '路由生成失败，请重新登录！'
                });
                store.dispatch('Logout').then(() => {
                  next({ path: '/user/login', query: { redirect: to.fullPath } });
                });
                return;
              }
              
              // 添加余料管理和半料管理路由
              constRoutes = addMaterialRoutes(constRoutes)
              
              // 添加主界面路由
              store.dispatch('UpdateAppRouter',  { constRoutes }).then(() => {
                // 根据roles权限生成可访问的路由表
                // 动态添加可访问路由表
                console.log('开始添加动态路由...');
                router.addRoutes(store.getters.addRouters);
                console.log('动态路由添加完成');
                
                const redirect = decodeURIComponent(from.query.redirect || to.path);
                console.log('重定向路径:', redirect, '当前路径:', to.path);
                
                if (to.path === redirect) {
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  console.log('使用replace模式跳转到当前路径');
                  next({ ...to, replace: true });
                } else {
                  // 跳转到目的路由
                  console.log('跳转到重定向路径:', redirect);
                  next({ path: redirect });
                }
              })
            })
          .catch((error) => {
            console.error('获取权限菜单失败:', error);
            notification.error({
              message: '系统提示',
              description: '请求用户信息失败，请重试！'
            });
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        console.log('权限列表已存在，直接跳转');
        next()
      }
    }
  } else {
    console.log('未检测到ACCESS_TOKEN');
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，如果进入的页面是login页面并且当前是OAuth2app环境，就进入OAuth2登录页面
      if (to.path === '/user/login' && isOAuth2AppEnv()) {
        console.log('OAuth2环境下访问登录页，重定向到OAuth2登录页');
        next({path: OAUTH2_LOGIN_PAGE_PATH})
      } else {
        // 在免登录白名单，直接进入
        console.log('在免登录白名单中，直接进入:', to.path);
        next()
      }
      NProgress.done()
    } else {
      // 如果当前是在OAuth2APP环境，就跳转到OAuth2登录页面
      let path = isOAuth2AppEnv() ? OAUTH2_LOGIN_PAGE_PATH : '/user/login'
      console.log('不在免登录白名单中，重定向到登录页:', path);
      next({ path: path, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach((to) => {
  NProgress.done() // finish progress bar
  
  // 添加页面加载完成后的检查，确保内容正常显示
  if (to.path.startsWith('/dashboard')) {
    console.log('进入仪表盘页面，检查页面内容...');
    // 延迟检查页面内容，给予足够的渲染时间
    setTimeout(() => {
      // 检查页面主体内容是否为空
      const mainContent = document.querySelector('.ant-layout-content');
      if (mainContent && (!mainContent.children || mainContent.children.length === 0)) {
        console.warn('检测到页面内容为空，可能出现白屏问题，准备刷新页面...');
        window.location.reload();
      } else {
        console.log('页面内容检查完成，显示正常');
      }
    }, 1000);
  }
})
